<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/news' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-select size="small" v-model="formInline.userState" placeholder="请选择">
          <el-option label="全部" value></el-option>
          <el-option label="正常" value="1"></el-option>
          <el-option label="已锁定" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label>
        <el-input size="small" v-model="formInline.userId" placeholder="输入用户Id"></el-input>
      </el-form-item>
      <el-form-item label>
        <el-input size="small" v-model="formInline.userName" placeholder="输入用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="mini" type="danger" @click="deleteCheackUser()">删除选中</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      @selection-change="selectChange"
      :data="userData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%;"
    >
      <el-table-column align="center" type="selection" width="50"></el-table-column>
      <el-table-column align="center" sortable prop="userId" label="用户编号" width="120"></el-table-column>
      <el-table-column align="center" prop="userName" label="用户名" width="120"></el-table-column>
      <el-table-column align="center" prop="userPass" label="密码" width="120"></el-table-column>
      <el-table-column align="center" prop="userSex" label="性别" width="120"></el-table-column>
      <el-table-column align="center" prop="userEmail" label="头像" min-width="120">
        <template slot-scope="scope">
          <img :src="scope.row.userUrl" width="80" height="80" />
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="userIntegral" label="用户积分" min-width="120"></el-table-column>
       <el-table-column sortable prop="adminTime" label="添加时间" width="300">
        <template slot-scope="scope">
          <div>{{scope.row.userTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="userState" label="状态" min-width="80">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.userState==1"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="editType(scope.$index, scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="success" @click="resetpwd(scope.$index, scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="30%"
      @click="closeDialog('edit')"
    >
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
        <el-form-item label="用户名" prop="userName">
          <el-input
            size="small"
            v-model="editForm.userName"
            auto-complete="off"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="userUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            action="/apis/admin/uploadImg"
          >
            <img
              v-if="editForm.userUrl"
              :src="editForm.userUrl"
              class="avatar"
              width="80"
              height="80"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="积分" prop="userIntegral">
          <el-input size="small" v-model="editForm.userIntegral" placeholder="请输入积分"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPass">
          <el-input size="small" v-model="editForm.userPass" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="userSex">
          <el-radio v-model="editForm.userSex" label="男">男</el-radio>
          <el-radio v-model="editForm.userSex" label="女">女</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('edit')">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import Pagination from "../Comm/Pagination";
import {
  userList,
  userState,
  userSave,
  userUpdate,
  userDelete,
  resetpwd,
  userAllDelete
} from "../../ajax/index";
export default {
  data() {
    return {
      loading: false, //是显示加载
      title: "添加用户",
      editFormVisible: false, //控制编辑页面显示与隐藏
      // 编辑与添加
      editForm: {
        userId: "",
        userName: "",
        userPass: "",
        userUrl: "",
        userSex: "",
        userIntegral: ""
      },
      // 选择数据
      selectdata: [],
      // rules表单验证
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        userPass: [
          { required: true, message: "请输入用户密码", trigger: "blur" }
        ],
        userSex: [{ required: true, message: "请选择性别", trigger: "blur" }]
      },
      // 请求数据参数
      formInline: {
        page: 1,
        limit: 10,
        userId: "",
        userName: "",
        userState: ""
      },
      //用户数据
      userData: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    };
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline);
  },
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取数据方法
    getdata(parameter) {
      this.loading = true;
      // 获取用户列表
      userList(parameter).then(res => {
        this.loading = false;
        if (res.code == 0) {
          this.$message({
            type: "info",
            message: res.data
          });
          this.listData = [];
          this.pageparm.currentPage = 1;
          this.pageparm.pageSize = 10;
          this.pageparm.total = 0;
        } else {
          this.userData = res.data;
          this.pageparm.currentPage = this.formInline.page;
          this.pageparm.pageSize = this.formInline.limit;
          this.pageparm.total = res.count;
        }
      });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.getdata(this.formInline);
    },
    //搜索事件
    search() {
      this.getdata(this.formInline);
    },
    // 修改type
    editType: function(index, row) {
      this.loading = true;
      let parm = {
        userId: "",
        userState: ""
      };
      parm.userId = row.userId;
      let state = row.userState;
      if (state == "1") {
        parm.userState = "0";
      } else {
        parm.userState = "1";
      }
      // 修改状态
      userState(parm).then(res => {
        this.loading = false;
        if (res.cpde == 0) {
          this.$message({
            type: "info",
            message: res.msg
          });
        } else {
          this.$message({
            type: "success",
            message: "状态修改成功"
          });
          this.getdata(this.formInline);
        }
      });
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "修改用户";
        this.editForm.userId = row.userId;
        this.editForm.userName = row.userName;
        this.editForm.userPass = row.userPass;
        this.editForm.userUrl = row.userUrl;
        this.editForm.userSex = row.userSex;
        this.editForm.userIntegral = row.userIntegral;
      } else {
        this.title = "添加用户";
        this.editForm.userId = "";
        this.editForm.userName = "";
        this.editForm.userPass = "";
        this.editForm.userUrl = "";
        this.editForm.userSex = "";
        this.editForm.userIntegral = "";
      }
    },
    // 编辑、添加提交方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          [userSave, userUpdate]
            [this.editForm.userId ? 1 : 0](this.editForm)
            .then(res => {
              this.editFormVisible = false;
              this.loading = false;
              if (res.code) {
                this.getdata(this.formInline);
                this.$message({
                  type: "success",
                  message: "数据保存成功！"
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.editFormVisible = false;
              this.loading = false;
              this.$message.error("保存失败，请稍后再试！");
            });
        } else {
          return false;
        }
      });
    },
    // 选择复选框事件
    selectChange(val) {
      this.selectdata = val;
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == "edit") {
        this.editFormVisible = false;
      }
    },
    // 删除用户
    deleteUser(index, row) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 删除
          userDelete({
            userId: row.userId
          })
            .then(res => {
              if (res.code) {
                this.$message({
                  type: "success",
                  message: "数据已删除!"
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.loading = false;
              this.$message.error("数据删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除！"
          });
        });
    },
    // 重置密码
    resetpwd(index, row) {
      this.$confirm("确定要重置密码吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          resetpwd({
            userId: row.userId
          })
            .then(res => {
              if (res.code) {
                this.$message({
                  type: "success",
                  message: "重置密码成功！"
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.loading = false;
              this.$message.error("重置密码失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消重置密码！"
          });
        });
    },
    //数据格式化
    changeArr(data) {
      var pos = {};
      var tree = [];
      var i = 0;
      while (data.length != 0) {
        if (data[i].pId == 0) {
          tree.push({
            id: data[i].id,
            name: data[i].name,
            pId: data[i].pId,
            open: data[i].open,
            checked: data[i].checked,
            children: []
          });
          pos[data[i].id] = [tree.length - 1];
          data.splice(i, 1);
          i--;
        } else {
          var posArr = pos[data[i].pId];
          if (posArr != undefined) {
            var obj = tree[posArr[0]];
            for (var j = 1; j < posArr.length; j++) {
              obj = obj.children[posArr[j]];
            }

            obj.children.push({
              id: data[i].id,
              name: data[i].name,
              pId: data[i].pId,
              open: data[i].open,
              checked: data[i].checked,
              children: []
            });
            pos[data[i].id] = posArr.concat([obj.children.length - 1]);
            data.splice(i, 1);
            i--;
          }
        }
        i++;
        if (i > data.length - 1) {
          i = 0;
        }
      }
      return tree;
    },
    // 选中菜单
    changemenu(arr) {
      let change = [];
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
          change.push(arr[i].id);
        }
      }
      return change;
    },
    handleAvatarSuccess(res, file) {
      // this.editForm.userUrl = URL.createObjectURL(file.raw);
      this.editForm.userUrl = res.data.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    deleteCheackUser() {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          userAllDelete({
            userIdList: this.selectdata.map(item => item.userId)
          })
            .then(res => {
              if (res.code) {
                this.$message({
                  type: "success",
                  message: "数据已删除!"
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.loading = false;
              this.$message.error("数据删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除！"
          });
        });
    }
  }
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  border: 1px dashed #d9d9d9;
}
</style>

 